package com.lse_from.config.interceptor

import org.apache.commons.lang3.time.DateFormatUtils
import org.springframework.lang.Nullable
import org.springframework.web.servlet.HandlerInterceptor
import org.springframework.web.servlet.ModelAndView
import java.lang.Exception
import java.net.InetAddress
import java.net.UnknownHostException
import java.util.*
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 * 跨域请求
 *
 * @author 祁雪
 */
class CrossInterceptorConfig : HandlerInterceptor {

    @Throws(Exception::class)
    override fun preHandle(request: HttpServletRequest, response: HttpServletResponse, handler: Any): Boolean {

        // 设置跨域
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"))
        //        response.setHeader("Access-Control-Allow-Origin", "*");
        //response.setHeader("Access-Control-Allow-Origin", "http://www.xn--iizl12d.cn");
        response.setHeader("Access-Control-Allow-Methods", "*")
        response.setHeader("Access-Control-Max-Age", "3600")
        response.setHeader("Access-Control-Allow-Headers", "*")
        response.setHeader("Access-Control-Allow-Credentials", "true")
        val ip = getIpAddr(request)
        println(
            "请求路径: ${request.servletPath}  ==>  IP: ${ip}  ==>  ${
                DateFormatUtils.format(
                    Date(),
                    "yyyy-MM-dd HH:mm:ss"
                )
            }"
        )

        return true
    }

    @Throws(Exception::class)
    override fun postHandle(
        request: HttpServletRequest,
        response: HttpServletResponse,
        handler: Any,
        @Nullable modelAndView: ModelAndView?
    ) {
    }

    @Throws(Exception::class)
    override fun afterCompletion(
        request: HttpServletRequest,
        response: HttpServletResponse,
        handler: Any,
        @Nullable ex: Exception?
    ) {
    }


    companion object {
        /**
         * 获取ip地址
         *
         * @param request
         * @return
         */
        fun getIpAddr(request: HttpServletRequest): String? {
            var ipAddress = request.getHeader("x-forwarded-for")
            if (ipAddress == null || ipAddress.length == 0 || "unknown".equals(ipAddress, ignoreCase = true)) {
                ipAddress = request.getHeader("Proxy-Client-IP")
            }
            if (ipAddress == null || ipAddress.length == 0 || "unknown".equals(ipAddress, ignoreCase = true)) {
                ipAddress = request.getHeader("WL-Proxy-Client-IP")
            }
            if (ipAddress == null || ipAddress.length == 0 || "unknown".equals(ipAddress, ignoreCase = true)) {
                ipAddress = request.remoteAddr
                val localIp = "127.0.0.1"
                val localIpv6 = "0:0:0:0:0:0:0:1"
                if (ipAddress == localIp || ipAddress == localIpv6) {
                    // 根据网卡取本机配置的IP
                    var inet: InetAddress? = null
                    try {
                        inet = InetAddress.getLocalHost()
                        ipAddress = inet.hostAddress
                    } catch (e: UnknownHostException) {
                        e.printStackTrace()
                    }
                }
            }
            // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
            val ipSeparate = ","
            val ipLength = 15
            if (ipAddress != null && ipAddress.length > ipLength) {
                if (ipAddress.indexOf(ipSeparate) > 0) {
                    ipAddress = ipAddress.substring(0, ipAddress.indexOf(ipSeparate))
                }
            }
            return ipAddress
        }
    }

}